<template>
  <div class="add-endpoint-container">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <div class="header-content">
          <el-avatar 
            :size="32" 
            :src="project?.iconUrl" 
            v-if="project?.iconUrl" 
            shape="square"
          />
              
          <div class="header-text">
            <h2>{{ project?.name }} - {{ ($route && $route.params && $route.params.endpointId) ? '编辑接口' : '添加接口' }}</h2>
            <p>{{ ($route && $route.params && $route.params.endpointId) ? '编辑现有接口配置' : '创建新的接口监控配置' }}</p>
          </div>
        </div>
      </template>
    </el-page-header>

    <div class="content-container full-width">
      <el-card class="form-card">
        <el-form
          ref="endpointFormRef"
          :model="endpointForm"
          :rules="rules"
          label-position="top"
          class="endpoint-form"
        >
          <!-- 基本信息区域 -->
          <div class="form-section basic-info-section compact">
            <div class="section-content">
              <el-row :gutter="12">
                <el-col :span="18">
                  <el-form-item label="接口名称" prop="name" class="compact-form-item">
                    <el-input
                      v-model="endpointForm.name"
                      placeholder="如: 获取用户信息API"
                      clearable
                      size="default"
                      class="endpoint-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="所属目录" prop="directoryId" class="compact-form-item">
                    <el-select
                      v-model="endpointForm.directoryId"
                      placeholder="选择目录"
                      clearable
                      size="default"
                      class="endpoint-input"
                    >
                      <el-option
                        label="默认目录"
                        :value="null"
                      />
                      <el-option
                        v-for="dir in directoryOptions"
                        :key="dir.id"
                        :label="dir.name"
                        :value="dir.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="24">
                  <div class="url-with-method">
                    <div class="method-select-wrapper">
                      <el-select
                        v-model="endpointForm.method"
                        placeholder="方法"
                        class="method-select"
                        size="default"
                      >
                        <el-option label="GET" value="GET" />
                        <el-option label="POST" value="POST" />
                        <el-option label="PUT" value="PUT" />
                        <el-option label="DELETE" value="DELETE" />
                        <el-option label="PATCH" value="PATCH" />
                      </el-select>
                    </div>
                    <div class="url-input-wrapper">
                      <el-input
                        v-model="endpointForm.url"
                        placeholder="https://api.example.com/users"
                        size="default"
                        class="endpoint-input url-input"
                        @input="handleUrlInput"
                      >
                        <template #append>
                          <el-button 
                            class="send-button"
                            @click="sendTestRequest"
                            :loading="sendingRequest"
                            :disabled="!endpointForm.url"
                          >
                            发送
                          </el-button>
                        </template>
                      </el-input>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 高级配置区域 -->
          <div class="form-section advanced-config-section">
            <div class="section-content no-padding-top">
              <el-tabs v-model="activeTab" class="config-tabs">
                <el-tab-pane label="查询参数" name="params">
                  <div class="params-editor">
                    <el-table :data="endpointForm.params" class="params-table" border>
                      <el-table-column label="参数名" width="200">
                        <template #default="scope">
                          <el-input 
                            v-model="scope.row.key" 
                            placeholder="如: page" 
                            size="small" 
                            @input="handleParamKeyInput(scope.$index)"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="参数值">
                        <template #default="scope">
                          <el-input 
                            v-model="scope.row.value" 
                            placeholder="如: 1" 
                            size="small"
                            @input="handleParamValueInput(scope.$index)"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="100" align="center">
                        <template #default="scope">
                          <el-button type="danger" @click="removeParam(scope.$index)" size="small" link>
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="请求头" name="headers">
                  <div class="headers-editor">
                    <el-table :data="endpointForm.headers" class="headers-table" border>
                      <el-table-column label="键" width="200">
                        <template #default="scope">
                          <el-select
                            v-model="scope.row.key"
                            filterable
                            allow-create
                            default-first-option
                            placeholder="如: Content-Type"
                            size="small"
                            @change="handleHeaderKeyInput(scope.$index)"
                          >
                            <el-option
                              v-for="item in commonHeaders"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column label="值">
                        <template #default="scope">
                          <el-input 
                            v-model="scope.row.value" 
                            placeholder="如: application/json" 
                            size="small"
                            @input="handleHeaderValueInput(scope.$index)"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="说明">
                        <template #default="scope">
                          <el-input 
                            v-model="scope.row.description" 
                            placeholder="如: 内容类型" 
                            size="small"
                            @input="handleHeaderDescriptionInput(scope.$index)"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="100" align="center">
                        <template #default="scope">
                          <el-button type="danger" @click="removeHeader(scope.$index)" size="small" link>
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="请求体" name="body" :disabled="endpointForm.method === 'GET'">
                  <div class="body-editor">
                    <el-form-item label="请求体类型" class="compact-form-item">
                      <el-select v-model="endpointForm.bodyType" style="width: 200px;" size="default" :disabled="endpointForm.method === 'GET'">
                        <el-option label="无" value="none" />
                        <el-option label="form-data" value="form-data" />
                        <el-option label="x-www-form-urlencoded" value="x-www-form-urlencoded" />
                        <el-option label="raw (原始数据)" value="raw" />
                        <el-option label="binary (二进制)" value="binary" />
                      </el-select>
                    </el-form-item>

                    <div v-if="endpointForm.bodyType !== 'none'" class="body-content">
                      <el-alert 
                        v-if="endpointForm.method === 'GET'" 
                        title="GET请求通常不包含请求体，此部分将被忽略" 
                        type="warning" 
                        show-icon 
                        style="margin-bottom: 16px;"
                      />
                      <div v-if="endpointForm.bodyType === 'raw'" class="raw-body-config">
                        <el-form-item label="数据类型" class="compact-form-item">
                          <el-select v-model="endpointForm.bodyRawType" style="width: 200px;" size="default">
                            <el-option label="JSON" value="json" />
                            <el-option label="XML" value="xml" />
                            <el-option label="Text" value="text" />
                            <el-option label="HTML" value="html" />
                          </el-select>
                        </el-form-item>
                        <el-input
                          v-model="endpointForm.bodyRaw"
                          type="textarea"
                          :rows="6"
                          placeholder="JSON/XML 等原始数据输入"
                          class="raw-body-input"
                          size="small"
                          :disabled="endpointForm.method === 'GET'"
                          @blur="formatJsonIfValid"
                        />
                      </div>

                      <div v-else class="form-body-config">
                        <el-table :data="endpointForm.bodyParams" class="body-table" border>
                          <el-table-column label="参数名" width="150">
                            <template #default="scope">
                              <el-input 
                                v-model="scope.row.key" 
                                placeholder="如: username" 
                                size="small"
                                @input="handleBodyParamKeyInput(scope.$index)"
                                :disabled="endpointForm.method === 'GET'"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="数据类型" width="120">
                            <template #default="scope">
                              <el-select v-model="scope.row.type" placeholder="数据类型" size="small" :disabled="endpointForm.method === 'GET'">
                                <el-option label="string" value="string" />
                                <el-option label="number" value="number" />
                                <el-option label="boolean" value="boolean" />
                                <el-option label="object" value="object" />
                                <el-option label="array" value="array" />
                              </el-select>
                            </template>
                          </el-table-column>
                          <el-table-column label="是否必需" width="100" align="center">
                            <template #default="scope">
                              <el-switch v-model="scope.row.required" size="small" :disabled="endpointForm.method === 'GET'" />
                            </template>
                          </el-table-column>
                          <el-table-column label="示例值">
                            <template #default="scope">
                              <el-input 
                                v-model="scope.row.example" 
                                placeholder="示例值" 
                                size="small"
                                @input="handleBodyParamExampleInput(scope.$index)"
                                :disabled="endpointForm.method === 'GET'"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="说明">
                            <template #default="scope">
                              <el-input 
                                v-model="scope.row.description" 
                                placeholder="参数说明" 
                                size="small"
                                @input="handleBodyParamDescriptionInput(scope.$index)"
                                :disabled="endpointForm.method === 'GET'"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="操作" width="100" align="center">
                            <template #default="scope">
                              <el-button 
                                type="danger" 
                                @click="removeBodyParam(scope.$index)" 
                                size="small" 
                                link
                                :disabled="endpointForm.method === 'GET'"
                              >
                                删除
                              </el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions compact">
            <el-button @click="goBack" size="default" class="action-btn cancel-btn">取消</el-button>
            <el-button
              type="primary"
              @click="saveEndpoint"
              :loading="saving"
              size="default"
              class="action-btn save-btn"
            >
              <template #default>
                <span v-if="!saving">保存配置</span>
                <span v-else>保存中...</span>
              </template>
            </el-button>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 测试请求结果弹窗 -->
    <el-dialog
      v-model="testResultVisible"
      title="测试请求结果"
      width="60%"
      class="test-result-dialog"
    >
      <div class="test-result-content">
        <el-tabs v-model="resultActiveTab">
          <el-tab-pane label="响应体" name="body">
            <div v-if="isJsonResponse" class="json-viewer">
              <pre><code v-html="highlightJson(formattedJson)"></code></pre>
            </div>
            <div v-else>
              <el-input
                v-model="testResult.body"
                type="textarea"
                :rows="10"
                readonly
                class="result-textarea"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="响应头" name="headers">
            <el-input
              v-model="testResult.headers"
              type="textarea"
              :rows="10"
              readonly
              class="result-textarea"
            />
          </el-tab-pane>
          <el-tab-pane label="基本信息" name="info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="状态码">
                <el-tag :type="getResultStatusType(testResult.status)">
                  {{ testResult.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="耗时">
                {{ testResult.duration }} ms
              </el-descriptions-item>
              <el-descriptions-item label="大小">
                {{ testResult.size }} bytes
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="testResultVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Connection,
  Plus,
  ArrowLeft,
  Promotion
} from '@element-plus/icons-vue'
import api from '../services/api'
import hljs from 'highlight.js/lib/core'
import json from 'highlight.js/lib/languages/json'
import 'highlight.js/styles/github.css'

hljs.registerLanguage('json', json)

export default {
  name: 'AddEndpoint',
  components: {
    Connection,
    Plus,
    ArrowLeft,
    Promotion
  },
  setup() {
    const route = useRoute()
    const router = useRouter()

    // 定义响应式变量
    const project = ref(null)
    const saving = ref(false)
    const endpointFormRef = ref(null)
    const activeTab = ref('params')
    const directoryOptions = ref([]) // 目录选项

    // 常用请求头
    const commonHeaders = [
      { label: 'Accept', value: 'Accept' },
      { label: 'Accept-Charset', value: 'Accept-Charset' },
      { label: 'Accept-Encoding', value: 'Accept-Encoding' },
      { label: 'Accept-Language', value: 'Accept-Language' },
      { label: 'Authorization', value: 'Authorization' },
      { label: 'Cache-Control', value: 'Cache-Control' },
      { label: 'Content-Type', value: 'Content-Type' },
      { label: 'Cookie', value: 'Cookie' },
      { label: 'User-Agent', value: 'User-Agent' }
    ]
    
    // 测试结果相关
    const testResultVisible = ref(false)
    const resultActiveTab = ref('body')
    const sendingRequest = ref(false)
    const testResult = reactive({
      status: 0,
      body: '',
      headers: '',
      duration: 0,
      size: 0
    })

    // 表单数据
    const endpointForm = reactive({
      name: '',
      url: '',
      method: 'GET',
      checkInterval: 60,
      expectedStatus: 200,
      params: [{ key: '', value: '' }], // 查询参数
      headers: [{ key: '', value: '', description: '' }], // 请求头
      bodyParams: [{ key: '', example: '', description: '' }], // 请求体参数
      requestBody: '', // 请求体内容
      requestHeaders: '{}', // 请求头JSON
      timeout: 5000, // 超时时间（毫秒）
      enabled: true, // 是否启用
      directoryId: null // 目录ID
    })

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入接口名称', trigger: 'blur' }
      ],
      url: [
        { required: true, message: '请输入接口URL', trigger: 'blur' },
        { type: 'url', message: '请输入有效的URL', trigger: 'blur' }
      ],
      method: [
        { required: true, message: '请选择请求方法', trigger: 'blur' }
      ],
      checkInterval: [
        { required: true, message: '请输入检查间隔', trigger: 'blur' },
        { type: 'number', message: '检查间隔必须为数字', trigger: 'blur' }
      ],
      expectedStatus: [
        { required: true, message: '请输入期望状态码', trigger: 'blur' },
        { type: 'number', message: '期望状态码必须为数字', trigger: 'blur' }
      ]
    }

    // 获取项目详情
    const fetchProject = async () => {
      try {
        const response = await api.get(`/projects/${route.params.projectId}`)
        project.value = response.data
      } catch (error) {
        ElMessage.error('获取项目详情失败: ' + error.message)
        // 使用模拟数据以便显示
        project.value = {
          id: route.params.projectId,
          name: '示例项目',
          description: '这是一个示例项目'
        }
      }
    }

    // 返回接口监控页面
    const goBack = () => {
      router.push({
        name: 'EndpointMonitor',
        params: { projectId: route.params.projectId }
      })
    }

    // 处理参数键输入
    const handleParamKeyInput = (index) => {
      // 如果是最后一个参数项且键不为空，则添加新的空参数项
      if (index === endpointForm.params.length - 1 && endpointForm.params[index].key) {
        endpointForm.params.push({ key: '', value: '' })
      }
    }

    // 处理参数值输入
    const handleParamValueInput = (index) => {
      // 如果是最后一个参数项且值不为空，则添加新的空参数项
      if (index === endpointForm.params.length - 1 && endpointForm.params[index].value) {
        endpointForm.params.push({ key: '', value: '' })
      }
    }

    // 删除参数
    const removeParam = (index) => {
      // 至少保留一个空参数项
      if (endpointForm.params.length > 1) {
        endpointForm.params.splice(index, 1)
      } else {
        // 如果只有一项，清空内容而不是删除
        endpointForm.params[0] = { key: '', value: '' }
      }
    }

    // 处理请求头键输入
    const handleHeaderKeyInput = (index) => {
      // 如果是最后一个请求头项且键不为空，则添加新的空请求头项
      if (index === endpointForm.headers.length - 1 && endpointForm.headers[index].key) {
        endpointForm.headers.push({ key: '', value: '', description: '' })
      }
    }

    // 处理请求头值输入
    const handleHeaderValueInput = (index) => {
      // 如果是最后一个请求头项且值不为空，则添加新的空请求头项
      if (index === endpointForm.headers.length - 1 && endpointForm.headers[index].value) {
        endpointForm.headers.push({ key: '', value: '', description: '' })
      }
    }

    // 处理请求头说明输入
    const handleHeaderDescriptionInput = (index) => {
      // 如果是最后一个请求头项且说明不为空，则添加新的空请求头项
      if (index === endpointForm.headers.length - 1 && endpointForm.headers[index].description) {
        endpointForm.headers.push({ key: '', value: '', description: '' })
      }
    }

    // 删除请求头
    const removeHeader = (index) => {
      // 至少保留一个请求头项
      if (endpointForm.headers.length > 1) {
        endpointForm.headers.splice(index, 1)
      } else {
        // 如果只有一项，清空内容而不是删除
        endpointForm.headers[0] = { key: '', value: '', description: '' }
      }
    }

    // 处理Body参数键输入
    const handleBodyParamKeyInput = (index) => {
      // 如果是最后一个Body参数项且键不为空，则添加新的空Body参数项
      if (index === endpointForm.bodyParams.length - 1 && endpointForm.bodyParams[index].key) {
        endpointForm.bodyParams.push({
          key: '',
          type: 'string',
          required: false,
          example: '',
          description: ''
        })
      }
    }

    // 处理Body参数示例值输入
    const handleBodyParamExampleInput = (index) => {
      // 如果是最后一个Body参数项且示例值不为空，则添加新的空Body参数项
      if (index === endpointForm.bodyParams.length - 1 && endpointForm.bodyParams[index].example) {
        endpointForm.bodyParams.push({
          key: '',
          type: 'string',
          required: false,
          example: '',
          description: ''
        })
      }
    }

    // 处理Body参数说明输入
    const handleBodyParamDescriptionInput = (index) => {
      // 如果是最后一个Body参数项且说明不为空，则添加新的空Body参数项
      if (index === endpointForm.bodyParams.length - 1 && endpointForm.bodyParams[index].description) {
        endpointForm.bodyParams.push({
          key: '',
          type: 'string',
          required: false,
          example: '',
          description: ''
        })
      }
    }

    // 删除Body参数
    const removeBodyParam = (index) => {
      // 至少保留一个Body参数项
      if (endpointForm.bodyParams.length > 1) {
        endpointForm.bodyParams.splice(index, 1)
      } else {
        // 如果只有一项，清空内容而不是删除
        endpointForm.bodyParams[0] = {
          key: '',
          type: 'string',
          required: false,
          example: '',
          description: ''
        }
      }
    }

    // 发送测试请求
    const sendTestRequest = async () => {
      if (!endpointForm.url) {
        ElMessage.warning('请输入URL')
        return
      }

      sendingRequest.value = true
      try {
        // 构建完整URL（包含查询参数）
        let fullUrl = endpointForm.url
        if (endpointForm.params.length > 0) {
          const queryParams = endpointForm.params
            .filter(param => param.key && param.value)
            .map(param => `${encodeURIComponent(param.key)}=${encodeURIComponent(param.value)}`)
            .join('&')

          if (queryParams) {
            fullUrl += (fullUrl.includes('?') ? '&' : '?') + queryParams
          }
        }

        // 构建请求头
        const headers = {}
        endpointForm.headers.forEach(header => {
          if (header.key && header.value) {
            headers[header.key] = header.value
          }
        })

        // 构建请求体
        let body = null
        if (endpointForm.bodyType === 'raw' && endpointForm.bodyRaw) {
          body = endpointForm.bodyRaw
        } else if ((endpointForm.bodyType === 'form-data' || endpointForm.bodyType === 'x-www-form-urlencoded') 
                  && endpointForm.bodyParams.length > 0) {
          const bodyObj = {}
          endpointForm.bodyParams.forEach(param => {
            if (param.key && param.value) {
              bodyObj[param.key] = param.value
            }
          })
          body = JSON.stringify(bodyObj)
        }

        // 记录开始时间
        const startTime = Date.now()

        // 发送请求
        const response = await fetch(fullUrl, {
          method: endpointForm.method,
          headers: headers,
          ...(endpointForm.method !== 'GET' && endpointForm.method !== 'HEAD' && { body: body })
        })

        // 计算耗时
        const duration = Date.now() - startTime

        // 获取响应体
        const responseBody = await response.text()

        // 获取响应头
        let responseHeaders = ''
        for (const [key, value] of response.headers.entries()) {
          responseHeaders += `${key}: ${value}\n`
        }

        // 更新测试结果
        testResult.status = response.status
        testResult.body = responseBody
        testResult.headers = responseHeaders
        testResult.duration = duration
        testResult.size = new Blob([responseBody]).size

        // 显示结果弹窗
        testResultVisible.value = true
      } catch (error) {
        ElMessage.error('请求发送失败: ' + error.message)
        
        // 显示错误信息
        testResult.status = 0
        testResult.body = '请求失败: ' + error.message
        testResult.headers = ''
        testResult.duration = 0
        testResult.size = 0
        testResultVisible.value = true
      } finally {
        sendingRequest.value = false
      }
    }

    // 获取结果状态标签类型
    const getResultStatusType = (status) => {
      if (status >= 200 && status < 300) {
        return 'success'
      } else if (status >= 300 && status < 400) {
        return 'warning'
      } else if (status >= 400) {
        return 'danger'
      }
      return 'info'
    }

    // 保存接口
    const saveEndpoint = async () => {
      endpointFormRef.value.validate(async (valid) => {
        if (valid) {
          saving.value = true
          try {
            // 过滤空的查询参数并转换为对象
            const filteredParams = endpointForm.params.filter(param => param.key && param.value);
            const paramsObj = {};
            filteredParams.forEach(param => {
              paramsObj[param.key] = param.value;
            });
            
            // 构建请求头对象
            const headersObj = {};
            endpointForm.headers.forEach(header => {
              if (header.key && header.value) {
                headersObj[header.key] = header.value;
              }
            });
            
            // 根据bodyType处理请求体
            let bodyObj = {};
            if (endpointForm.bodyType === 'form-data' || endpointForm.bodyType === 'x-www-form-urlencoded') {
              // 将bodyParams转换为对象
              endpointForm.bodyParams.forEach(param => {
                if (param.key && param.example) {
                  bodyObj[param.key] = param.example;
                }
              });
            }
            
            // 构造请求数据 (只包含后端需要的字段)
            const endpointData = {
              name: endpointForm.name,
              url: endpointForm.url,
              method: endpointForm.method,
              checkInterval: endpointForm.checkInterval,
              expectedStatus: endpointForm.expectedStatus,
              params: paramsObj, // 查询参数对象
              requestHeaders: headersObj, // 请求头对象
              requestBody: endpointForm.bodyType === 'raw' ? endpointForm.bodyRaw : bodyObj, // 请求体对象或字符串
              bodyType: endpointForm.bodyType, // 添加bodyType字段
              timeout: endpointForm.timeout,
              enabled: endpointForm.enabled,
              directoryId: endpointForm.directoryId // 添加目录ID
            }

            if (route && route.params && route.params.endpointId) {
              // 编辑模式 - 更新接口
              await api.put(`/endpoints/${route.params.endpointId}`, endpointData)
              ElMessage.success('更新成功')
            } else {
              // 新增模式 - 创建接口
              await api.post(`/endpoints/project/${route.params.projectId}`, endpointData)
              ElMessage.success('添加成功')
            }
            router.push(`/project/${route.params.projectId}/endpoints`)
          } catch (error) {
            // 处理错误
            ElMessage.error((route && route.params && route.params.endpointId ? '更新' : '添加') + '失败: ' + (error.response?.data?.message || error.message))
            saving.value = false
          }
        } else {
          // 表单验证失败
          saving.value = false
        }
      })
    }

    // 处理URL输入变化
    const handleUrlInput = () => {
      // 当URL改变时，自动解析查询参数
      parseUrlParams()
    }

    // 获取项目目录列表
    const fetchDirectories = async () => {
      try {
        const response = await api.get(`/directories/project/${route.params.projectId}`)
        // 目录选项
        directoryOptions.value = response.data.map(dir => ({
          id: dir.id,
          name: dir.name
        }))
      } catch (error) {
        console.error('获取目录列表失败:', error)
        ElMessage.error('获取目录列表失败: ' + error.message)
      }
    }

    onMounted(() => {
      console.log('route.params.endpointId:', route.params?.endpointId);
      console.log('完整route对象:', route);
      fetchProject()
      fetchDirectories() // 获取目录列表
      // 如果有endpointId参数，说明是编辑模式
      if (route && route.params && route.params.endpointId) {
        fetchEndpoint(route.params.endpointId)
      } else {
        // 新增模式下，检查是否有目录ID查询参数
        if (route.query.directoryId !== undefined) {
          // 处理传入的目录ID，'null'字符串表示默认目录
          endpointForm.directoryId = route.query.directoryId === 'null' ? null : 
                                   route.query.directoryId === null ? null : 
                                   parseInt(route.query.directoryId)
        }
      }
    })

    // 解析URL中的查询参数并填充到表格中
    const parseUrlParams = () => {
      if (endpointForm.url) {
        try {
          const urlObj = new URL(endpointForm.url)
          const searchParams = urlObj.searchParams
          
          // 只有在参数表单为空时才自动填充URL参数
          const isEmpty = endpointForm.params.length === 1 && 
                         !endpointForm.params[0].key && 
                         !endpointForm.params[0].value;
          
          if (isEmpty) {
            // 清空现有的参数（除了最后一行空行）
            endpointForm.params = [{ key: '', value: '' }]
            
            // 添加解析出的查询参数
            let index = 0
            for (const [key, value] of searchParams) {
              if (index < endpointForm.params.length) {
                endpointForm.params[index].key = key
                endpointForm.params[index].value = value
              } else {
                endpointForm.params.push({ key, value })
              }
              index++
            }
            
            // 确保至少有一个空行
            if (endpointForm.params.length === 0 || 
                (endpointForm.params[endpointForm.params.length - 1].key || 
                 endpointForm.params[endpointForm.params.length - 1].value)) {
              endpointForm.params.push({ key: '', value: '' })
            }
          }
        } catch (e) {
          // URL格式不正确，不做处理
          console.log('URL格式不正确，无法解析查询参数')
        }
      }
    }

    // 获取要编辑的接口信息
    const fetchEndpoint = async (endpointId) => {
      try {
        const response = await api.get(`/endpoints/${endpointId}`);
        const endpoint = response.data;
        
        // 填充表单数据
        endpointForm.name = endpoint.name;
        endpointForm.url = endpoint.url;
        endpointForm.method = endpoint.method;
        endpointForm.checkInterval = endpoint.checkInterval;
        endpointForm.expectedStatus = endpoint.expectedStatus;
        endpointForm.timeout = endpoint.timeout || 5000;
        endpointForm.enabled = endpoint.enabled !== undefined ? endpoint.enabled : true;
        endpointForm.directoryId = endpoint.directoryId || null;
        endpointForm.bodyType = endpoint.bodyType || 'none';
        
        // 处理查询参数
        if (endpoint.params) {
          try {
            // 尝试解析params JSON字符串为对象
            const paramsObj = JSON.parse(endpoint.params);
            if (typeof paramsObj === 'object' && paramsObj !== null && !Array.isArray(paramsObj)) {
              // 如果是对象，转换为数组格式
              endpointForm.params = Object.keys(paramsObj).map(key => ({
                key,
                value: paramsObj[key]
              }));
              
              // 确保至少有一个空行
              if (endpointForm.params.length === 0 || 
                  (endpointForm.params[endpointForm.params.length-1].key !== '' || 
                   endpointForm.params[endpointForm.params.length-1].value !== '')) {
                endpointForm.params.push({ key: '', value: '' });
              }
            } else {
              endpointForm.params = [{ key: '', value: '' }];
            }
          } catch (e) {
            // 如果不是有效的JSON，保持原来的处理方式
            console.error('解析查询参数失败:', e);
            endpointForm.params = [{ key: '', value: '' }];
          }
        } else {
          endpointForm.params = [{ key: '', value: '' }];
        }
        
        // 处理请求头
        if (endpoint.requestHeaders) {
          try {
            // 解析requestHeaders JSON字符串为对象
            const headersObj = JSON.parse(endpoint.requestHeaders);
            if (typeof headersObj === 'object' && headersObj !== null && !Array.isArray(headersObj)) {
              endpointForm.headers = Object.keys(headersObj).map(key => ({
                key,
                value: headersObj[key],
                description: ''
              }));
              
              // 确保至少有一个空行
              if (endpointForm.headers.length === 0) {
                endpointForm.headers.push({ key: '', value: '', description: '' });
              }
            } else {
              endpointForm.headers = [{ key: '', value: '', description: '' }];
            }
          } catch (e) {
            console.error('解析请求头失败:', e);
            endpointForm.headers = [{ key: '', value: '', description: '' }];
          }
        } else {
          endpointForm.headers = [{ key: '', value: '', description: '' }];
        }
        
        // 处理请求体
        if (endpoint.requestBody) {
          try {
            // 尝试解析请求体
            const parsedBody = JSON.parse(endpoint.requestBody);
            if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
              // 如果是对象
              endpointForm.bodyType = 'form-data';
              endpointForm.bodyParams = Object.keys(parsedBody).map(key => ({
                key,
                type: 'string',
                required: false,
                example: parsedBody[key],
                description: ''
              }));
              
              // 确保至少有一个空行
              if (endpointForm.bodyParams.length === 0) {
                endpointForm.bodyParams.push({
                  key: '',
                  type: 'string',
                  required: false,
                  example: '',
                  description: ''
                });
              }
            } else {
              // 否则是raw类型
              endpointForm.bodyType = 'raw';
              endpointForm.bodyRaw = endpoint.requestBody;
              endpointForm.bodyRawType = 'json';
            }
          } catch (e) {
            // 如果不是有效的JSON，当作raw文本处理
            endpointForm.bodyType = 'raw';
            endpointForm.bodyRaw = endpoint.requestBody;
            endpointForm.bodyRawType = 'text';
          }
        } else {
          // 默认值
          endpointForm.bodyType = 'none';
          endpointForm.bodyParams = [{
            key: '',
            type: 'string',
            required: false,
            example: '',
            description: ''
          }];
        }
        
        // 特别处理raw类型的请求体
        if (endpoint.bodyType === 'raw' && endpoint.requestBody) {
          endpointForm.bodyType = 'raw';
          endpointForm.bodyRaw = endpoint.requestBody;
          // 尝试判断raw数据的类型
          try {
            JSON.parse(endpoint.requestBody);
            endpointForm.bodyRawType = 'json';
          } catch (e) {
            // 如果不能解析为JSON，则默认为text
            endpointForm.bodyRawType = 'text';
          }
        }
        
        // 解析URL中的查询参数并填充到表格中
        parseUrlParams();
      } catch (error) {
        console.error('获取接口信息失败:', error);
        ElMessage.error('获取接口信息失败: ' + (error.response?.data?.message || error.message));
      }
    }

    // 判断是否为JSON响应
    const isJsonResponse = computed(() => {
      if (!testResult.body) return false
      
      try {
        JSON.parse(testResult.body)
        return true
      } catch (e) {
        return false
      }
    })

    // 格式化JSON显示
    const formattedJson = computed(() => {
      if (!testResult.body) return ''
      
      try {
        const jsonObj = JSON.parse(testResult.body)
        return JSON.stringify(jsonObj, null, 2)
      } catch (e) {
        return testResult.body
      }
    })

    // JSON高亮函数（使用highlight.js）
    const highlightJson = (json) => {
      try {
        // 确保hljs已正确加载和初始化
        if (hljs && typeof hljs.highlight === 'function') {
          const highlighted = hljs.highlight(json, {language: 'json'})
          return highlighted.value
        } else {
          // 如果highlight.js未正确加载，返回原始内容
          console.warn('highlight.js 未正确初始化')
          return json
        }
      } catch (e) {
        // 如果highlight.js处理失败，返回原始内容
        console.error('JSON 高亮处理失败:', e)
        return json
      }
    }

    // 格式化JSON（如果有效）
    const formatJsonIfValid = () => {
      // 只有当bodyType为raw且bodyRawType为json时才格式化
      if (endpointForm.bodyType === 'raw' && endpointForm.bodyRawType === 'json' && endpointForm.bodyRaw) {
        try {
          // 尝试解析JSON
          const parsed = JSON.parse(endpointForm.bodyRaw);
          // 如果解析成功，则格式化并更新
          endpointForm.bodyRaw = JSON.stringify(parsed, null, 2);
        } catch (e) {
          // 如果JSON无效，不执行任何操作
          console.log('JSON格式无效，无法格式化');
        }
      }
    }

    return {
      endpointFormRef,
      activeTab,
      saving,
      project,
      endpointForm,
      rules,
      directoryOptions, // 添加目录选项
      goBack,
      removeParam,
      removeHeader,
      removeBodyParam,
      handleParamKeyInput,
      handleParamValueInput,
      handleHeaderKeyInput,
      handleHeaderValueInput,
      handleHeaderDescriptionInput,
      handleBodyParamKeyInput,
      handleBodyParamExampleInput,
      handleBodyParamDescriptionInput,
      // 测试请求相关
      sendingRequest,
      sendTestRequest,
      testResultVisible,
      resultActiveTab,
      testResult,
      getResultStatusType,
      saveEndpoint,
      Promotion,
      isJsonResponse,
      formattedJson,
      // 常用请求头
      commonHeaders,
      // URL处理
      handleUrlInput,
      // JSON格式化和高亮
      formatJsonIfValid,
      highlightJson
    }
  }
}
</script>

<style scoped>
.add-endpoint-container {
  width: 100%;
  margin: 0;
  padding: 0;
  background-color: #f9f6e7;
  min-height: 100vh;
}

/* JSON高亮样式 */
.json-viewer {
  background-color: #f4f4f4;
  border-radius: 4px;
  padding: 12px;
  overflow: auto;
}

.json-viewer pre {
  margin: 0;
  font-family: 'Consolas', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.page-header {
  margin-bottom: 16px;
  background-color: #f0ebe0;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid #e0d4b4;
}

.header-content h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #5a4a3a;
}

.header-content p {
  margin: 4px 0 0 0;
  color: #7a6b5a;
  font-size: 14px;
}

.project-info-header {
  padding: 12px 20px;
  border-bottom: 1px solid #e0d4b4;
  background: #f8f6ee;
}

.back-button {
  color: #7a6b5a;
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.back-button:hover {
  color: #5a4a3a;
  background-color: rgba(0, 0, 0, 0.05);
  transform: translateY(-1px);
}

.form-card {
  border-radius: 0;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: none;
  background: #fffdf8;
  overflow: hidden;
  margin-bottom: 0;
}

.endpoint-form {
  padding: 0;
}

.form-section {
  border-bottom: 1px solid #e0d4b4;
}

.form-section:last-child {
  border-bottom: none;
}

.basic-info-section {
  background: #fffdf8;
}

.advanced-config-section {
  background: #fffdf8;
}

.compact {
  padding: 12px 20px;
}

.section-content {
  padding: 0 20px 16px 20px;
}

.section-content.no-padding-top {
  padding-top: 0;
}

.compact-form-item {
  margin-bottom: 16px;
}

.compact-form-item :deep(.el-form-item__label) {
  font-size: 13px;
  margin-bottom: 4px;
  color: #5a4a3a;
  font-weight: 500;
}

.endpoint-input :deep(.el-input__wrapper) {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.endpoint-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 1px 3px rgba(205, 170, 82, 0.3);
  border-color: #cdaa52;
}

.method-select {
  width: 100px;
}

.url-with-method {
  display: flex;
  gap: 0;
  align-items: flex-start;
}

.method-select-wrapper {
  flex: 0 0 100px;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.url-input-wrapper {
  flex: 1;
  margin-bottom: 0;
}

.url-input :deep(.el-input__wrapper) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.send-button {
  background: linear-gradient(135deg, #cdaa52, #b8943d);
  border: none;
  color: white !important; /* 确保字体始终为白色 */
  transition: all 0.3s ease;
}

.send-button:hover {
  background: linear-gradient(135deg, #b8943d, #a37e2d);
  box-shadow: 0 4px 8px rgba(205, 170, 82, 0.3);
  color: white !important; /* 悬停时也保持白色字体 */
}

.send-button:disabled {
  background: #d1c5a1;
  color: #f8f6ee !important; /* 禁用时使用浅米色 */
}

.config-tabs {
  border-radius: 0;
  overflow: hidden;
}

:deep(.config-tabs .el-tabs__header) {
  margin: 0;
  background: #f8f6ee;
  padding: 0 20px;
  border-bottom: 1px solid #e0d4b4;
}

:deep(.config-tabs .el-tabs__content) {
  padding: 16px 20px;
}

:deep(.config-tabs .el-tabs__item) {
  font-weight: 500;
  color: #7a6b5a;
  height: 44px;
  line-height: 44px;
  font-size: 14px;
  transition: all 0.3s ease;
}

:deep(.config-tabs .el-tabs__item:hover) {
  color: #cdaa52;
}

:deep(.config-tabs .el-tabs__item.is-active) {
  color: #cdaa52;
  font-weight: 600;
}

:deep(.config-tabs .el-tabs__active-bar) {
  background-color: #cdaa52;
}

.params-table,
.headers-table,
.body-table {
  margin-top: 0;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e0d4b4;
}

.raw-body-input {
  margin-top: 12px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin: 20px 20px;
  padding-top: 20px;
  border-top: 1px solid #e0d4b4;
}

.form-actions.compact {
  margin: 20px 20px;
  padding-top: 20px;
}

.action-btn {
  border-radius: 6px;
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.cancel-btn {
  border: 1px solid #d1c5a1;
  color: #7a6b5a;
  background: #fffdf8;
}

.cancel-btn:hover {
  background: #f8f6ee;
  border-color: #cdaa52;
  color: #5a4a3a;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}

.save-btn {
  background: linear-gradient(135deg, #cdaa52, #b8943d);
  border: none;
  color: white;
  box-shadow: 0 2px 6px rgba(205, 170, 82, 0.3);
}

.save-btn:hover {
  background: linear-gradient(135deg, #b8943d, #a37e2d);
  box-shadow: 0 4px 12px rgba(205, 170, 82, 0.4);
  transform: translateY(-2px);
}

/* 表格样式优化 */
:deep(.el-table) {
  --el-table-border-color: #e0d4b4;
  --el-table-header-bg-color: #f8f6ee;
  border-radius: 6px;
  overflow: hidden;
  font-size: 13px;
}

:deep(.el-table th) {
  background-color: #f8f6ee;
  color: #5a4a3a;
  font-weight: 600;
  padding: 10px 12px;
}

:deep(.el-table td) {
  padding: 10px 12px;
  transition: background-color 0.2s ease;
}

:deep(.el-table tr) {
  background-color: white;
}

:deep(.el-table tr:hover) {
  background-color: #fdfbf4;
}

.json-viewer {
  background-color: #fffdf8;
  border-radius: 6px;
  padding: 16px;
  max-height: 400px;
  overflow: auto;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  border: 1px solid #e0d4b4;
}

.text-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  padding: 16px;
  background-color: #fffdf8;
  border-radius: 6px;
  max-height: 400px;
  overflow: auto;
  border: 1px solid #e0d4b4;
}

.json-viewer pre {
  margin: 0;
  white-space: pre;
}

.json-viewer code {
  white-space: pre;
}

.json-viewer .key {
  color: #cdaa52;
  font-weight: bold;
}

.json-viewer .string {
  color: #690;
}

.json-viewer .number {
  color: #905;
}

.json-viewer .boolean {
  color: #905;
}

.json-viewer .null {
  color: #999;
}

.result-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.test-result-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.test-result-dialog :deep(.el-dialog__header) {
  background: #f8f6ee;
  border-bottom: 1px solid #e0d4b4;
  padding: 16px 20px;
}

.test-result-dialog :deep(.el-dialog__title) {
  color: #5a4a3a;
  font-weight: 600;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-endpoint-container {
    padding: 0;
  }
  
  .project-info-header {
    padding: 10px 16px;
  }
  
  .compact {
    padding: 10px 16px;
  }
  
  .section-content {
    padding: 0 16px 12px 16px;
  }
  
  .section-content.no-padding-top {
    padding-top: 0;
  }
  
  .back-button {
    font-size: 13px;
    padding: 4px 8px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .el-col {
    width: 100%;
  }
  
  .form-actions {
    margin: 16px 16px;
    padding-top: 16px;
    gap: 12px;
  }
  
  .form-actions.compact {
    margin: 16px 16px;
    padding-top: 16px;
  }
  
  :deep(.config-tabs .el-tabs__content) {
    padding: 12px 16px;
  }
  
  :deep(.config-tabs .el-tabs__header) {
    padding: 0 16px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px 8px;
  }
  
  :deep(.config-tabs .el-tabs__item) {
    height: 40px;
    line-height: 40px;
    font-size: 13px;
  }
  
  .action-btn {
    padding: 8px 16px;
    font-size: 13px;
  }
  
  .url-with-method {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .method-select-wrapper {
    flex: 0 0 auto;
  }
  
  .method-select {
    width: 100%;
  }
  
  .url-input :deep(.el-input__wrapper) {
    border-top-left-radius: 8px;
    border-bottom-left-radius: 8px;
  }
  
  .compact-form-item {
    margin-bottom: 12px;
  }
}
</style>